import { createStore } from 'vuex'
//在vuex初始化时导入插件
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    goodsList: [], // 购物车里面商品数据
  },
  getters: {
    cartNum(state){ // 购物车总数
      let num = 0;
      state.goodsList.forEach(item => {
        num+=item.buyNum
      });
      return num;
    }
  },
  mutations: {
    savaList(state,val){ // 保存购物车数据的方法
      let index = state.goodsList.findIndex(item => item.checkid == val.checkid);
      if (index>-1){
        state.goodsList[index].buyNum += val.buyNum;
      } else {
        state.goodsList.push(val);
      }
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    new persist({
      storage: window.localStorage,
    }),
  ],
})
